package com.dfa.nypl.news;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParserException;

import com.dfa.nypl.common.EscapeHTML;
import com.dfa.nypl.common.Utils;
import com.dfa.nypl.common.WebService;
import com.dfa.nypl.entity.TopHeadline;
import com.dfa.nypl.main.R;
import com.dfa.nypl.view.LoaderImageView;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class News extends Activity {
	private LinearLayout videoLayout, photoLayout, textLayout, headlineLayout;
	private LinearLayout progressbarLayout;

	private TextView textTitle, textBody, photoTitle, videoTitle, videoBody,
			headlineTitle, headlineBody;

	private WebView videoWebview;

	private TopHeadline mTopHeadline;

	private LinearLayout headlinePhotoIconLayout;

	private TelephonyManager telephonyManager;
	private WakeLock lock;
	private ConnectivityManager connectivityManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news_screen);

		connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		initWakeLock();

		videoLayout = (LinearLayout) findViewById(R.id.headline_video_layout);
		photoLayout = (LinearLayout) findViewById(R.id.headline_photo_layout);
		textLayout = (LinearLayout) findViewById(R.id.headline_text_layout);
		headlineLayout = (LinearLayout) findViewById(R.id.headline_headline_layout);
		progressbarLayout = (LinearLayout) findViewById(R.id.healine_progressbar_layout);
		// videoWebviewLayout = (LinearLayout)
		// findViewById(R.id.headline_video_webview_layout);

		textTitle = (TextView) findViewById(R.id.headline_text_title);
		textBody = (TextView) findViewById(R.id.headline_text_body);
		photoTitle = (TextView) findViewById(R.id.headline_photo_body);
		videoTitle = (TextView) findViewById(R.id.headline_video_title);
		videoBody = (TextView) findViewById(R.id.headline_video_body);
		headlineTitle = (TextView) findViewById(R.id.headline_headline_title);
		headlineBody = (TextView) findViewById(R.id.headline_headline_body);

		headlinePhotoIconLayout = (LinearLayout) findViewById(R.id.headline_photo_icon_layout);

		videoWebview = (WebView) findViewById(R.id.headline_video_webview);
		configWebView(videoWebview);

		if (isConnected()) {
			new ViewScreenTask().execute();
		} else {
			Toast.makeText(News.this, "Network unable to connect",
					Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		lock.release();
	}

	@Override
	protected void onResume() {
		super.onResume();
		lock.acquire();

	}

	private void initWakeLock() {
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		lock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
				| PowerManager.ON_AFTER_RELEASE, "LiveGPSTraking");
	}

	private boolean isConnected() {
		if (telephonyManager == null || connectivityManager == null) {
			return false;
		}

		final boolean roaming = telephonyManager.isNetworkRoaming();
		final NetworkInfo info = connectivityManager.getActiveNetworkInfo();

		return info != null && info.isConnected() && !roaming;
	}

	private void setVideoScreen() {
		videoLayout.setVisibility(View.VISIBLE);
		photoLayout.setVisibility(View.GONE);
		textLayout.setVisibility(View.GONE);
		headlineLayout.setVisibility(View.GONE);
	}

	private void setPhotoScreen() {
		videoLayout.setVisibility(View.GONE);
		photoLayout.setVisibility(View.VISIBLE);
		textLayout.setVisibility(View.GONE);
		headlineLayout.setVisibility(View.GONE);
	}

	private void setTextScreen() {
		videoLayout.setVisibility(View.GONE);
		photoLayout.setVisibility(View.GONE);
		textLayout.setVisibility(View.VISIBLE);
		headlineLayout.setVisibility(View.GONE);
	}

	private void setHeadlineScreen() {
		videoLayout.setVisibility(View.GONE);
		photoLayout.setVisibility(View.GONE);
		textLayout.setVisibility(View.GONE);
		headlineLayout.setVisibility(View.VISIBLE);
	}

	private class ViewScreenTask extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;

		public ViewScreenTask() {
			dialog = new ProgressDialog(News.this);
			dialog.setMessage("Waiting...");
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (mTopHeadline != null) {
				String featureType = mTopHeadline.getFeatureType();

				if (featureType.equals("Video")) {
					setVideoScreen();
					videoTitle.setText(mTopHeadline.getTitle());
					videoBody.setText(mTopHeadline.getBody());

					String youtubeUrl = mTopHeadline.getYouTubeEmbeddedCode();

					int width = 263;
					int height = 178;

					youtubeUrl = getSrcVideo(youtubeUrl);

					if (!isConnected()) {
						progressbarLayout.setVisibility(View.GONE);
						Toast.makeText(News.this, "Network unable to connect",
								Toast.LENGTH_SHORT).show();

					} else {
						String content = "<html>"
								+ "<head>"
								+ "<style type=\"text/css\">"
								+ " body {background-color: grey;}"
								+ "</style>"
								+ "</head>"
								+ "<body style=\"margin:0;\">"
								+ "<div align=\"center\">"
								+ ""
								+ replaceSize(EscapeHTML.unescapeHTML(
										mTopHeadline.getYouTubeEmbeddedCode(),
										0)) + "" + "</div></body></html>" + "";

						System.out.println("CONTENT=" + content);

						progressbarLayout.setVisibility(View.VISIBLE);
						videoWebview.loadDataWithBaseURL(null, content,
								"text/html", "UTF-8", null);

						videoWebview.setWebChromeClient(new WebChromeClient() {
							public void onProgressChanged(WebView view,
									int progress) {
								if (progress == 100)
									progressbarLayout.setVisibility(View.GONE);
							}
						});
					}

				} else if (featureType.equals("Text")) {
					setTextScreen();

					textTitle.setText(mTopHeadline.getTitle());
					textBody.setText(mTopHeadline.getBody());

				} else if (featureType.equals("Headline")) {
					setHeadlineScreen();
					headlineTitle.setText(mTopHeadline.getTitle());
					headlineBody.setText(mTopHeadline.getBody());

				} else if (featureType.equals("Photo")) {
					setPhotoScreen();

					photoTitle.setText(mTopHeadline.getTitle());

					String photoUrl = News.this.getResources().getString(
							R.string.amazonaw_url);
					String tmp = mTopHeadline.getPhotoUidID().substring(0, 3);
					photoUrl += tmp + "/";
					photoUrl += mTopHeadline.getPhotoUidID();
					System.out.println("URL=" + photoUrl);
					LoaderImageView headlinePhotoIcon = new LoaderImageView(
							News.this, photoUrl);

					headlinePhotoIcon.setLayoutParams(new LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT));
					headlinePhotoIconLayout.addView(headlinePhotoIcon);

				}
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			try {
				mTopHeadline = WebService.getSingletonService()
						.getTopHeadline();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return null;
		}
	}

	private int[] getSizeInfo(String url) {
		String widthStr = "width";
		String heightStr = "height";
		int len1 = widthStr.length() + 2;
		int len2 = heightStr.length() + 2;
		String subWUrl = url.substring(url.indexOf(widthStr) + len1);
		String width = subWUrl.substring(0, subWUrl.indexOf("\""));

		String subHUrl = url.substring(url.indexOf(heightStr) + len2);
		String height = subHUrl.substring(0, subHUrl.indexOf("\""));

		int[] size = new int[] { Integer.parseInt(width),
				Integer.parseInt(height) };
		return size;
	}

	private void configWebView(WebView v) {
		v.getSettings().setJavaScriptEnabled(true);
		v.getSettings().setPluginsEnabled(true);
		v.setVerticalScrollBarEnabled(false);
		v.setHorizontalScrollBarEnabled(false);

	}

	public String getSrcVideo(String url) {
		String str = "src=\"";
		String subStr = url.substring(url.indexOf(str) + str.length());
		subStr = subStr.substring(0, subStr.indexOf("\""));
		System.out.println(":::" + subStr);
		return subStr;
	}

	public String replaceSize(String url) {
		String regexStringWidth = "width=\"[0-9][0-9][0-9]\"";
		String regexStringHeight = "height=\"[0-9][0-9][0-9]\"";
		String replaceStringWidth = "width='263'";
		String replaceStringHeight = "height='178'";
		Matcher matcher = null;
		Pattern pattern = null;
		String output = null;

		pattern = Pattern.compile(regexStringWidth);
		matcher = pattern.matcher(url);
		output = matcher.replaceAll(replaceStringWidth);

		pattern = Pattern.compile(regexStringHeight);
		matcher = pattern.matcher(output);
		output = matcher.replaceAll(replaceStringHeight);
//		String str = "\\\"";
//		output = output.replace("\"", str);
		return output;
	}

}
